package com.zzsy.carosshopprojects.activitys.home.mainpage.main;

import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.adapter.HolderRecyclerAdapter;
import com.king.base.util.ToastUtils;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.maincardmanager.MainCardManagerAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.charge.ChoseOilNewAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.scan.ScanAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.incrementservice.IncrementServiceAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.oneclickoil.OneClickOilAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.orderamount.OrderAmountAc;
import com.zzsy.carosshopprojects.activitys.home.mainpage.quickjoinoil.QuickJoinOilAc;
import com.zzsy.carosshopprojects.adapter.HomePageAdapter;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.base.FunctionTypeEnum;
import com.zzsy.carosshopprojects.bean.HomePageBean;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.util.SPUtil;
import com.zzsy.carosshopprojects.util.ThrottleFirstUtil;
import com.zzsy.carosshopprojects.util.ViewBgUtil;
import com.zzsy.carosshopprojects.view.GridDividerItemDecoration;
import com.zzsy.carosshopprojects.view.dialog.GoUpPopupDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindDimen;
import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 项目主页
 */
public class HomePageFragment extends BaseFragment implements HolderRecyclerAdapter.OnItemClickListener {

    public static HomePageFragment newInstance() {
        HomePageFragment homePageFragment = new HomePageFragment();
        return homePageFragment;
    }

    private String[] permissionArrs = {Manifest.permission.CAMERA};
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.tv_role)
    TextView tvRole;//顶部显示哪种角色
    @BindView(R.id.ly_top)
    LinearLayout lyTop;//设置顶部背景颜色
    @BindView(R.id.ll_order_data)
    LinearLayout lyOrderData;//顶部订单显示与否
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;//顶部订单时间
    @BindView(R.id.tv_oils_data)
    TextView tvOilsData;//顶部订单内容
    @BindView(R.id.tv_leftName)
    TextView tvLeftName;//顶部根据账号角色显示左边标题
    @BindView(R.id.tv_LeftAccount)
    TextView tvLeftAccount;//顶部根据账号角色显示左边内容
    @BindView(R.id.tv_RightName)
    TextView tvRightName;//顶部根据账号角色显示右边标题
    @BindView(R.id.tv_RightAccount)
    TextView tvRightAccount;//顶部根据账号角色显示右边内容
    @BindView(R.id.recycleView)
    RecyclerView recycleView;//底部列表
    @BindDimen(R.dimen.p_30)
    int p_20;//获取尺寸大小
    private HomePageAdapter homePageAdapter;
    private MainPageMode mainPageMode;
    private List<HomePageBean> list = new ArrayList<>();
    private boolean b = true;

    @Override
    protected int initLayout() {
        return R.layout.fg_homepage;
    }

    @Override
    protected void initView(View view) {
        //lyTop.setBackground(ViewBgUtil.setBg(p_20, Color.parseColor(ConfigureFile.ColorWhite)));
        lyOrderData.setBackground(ViewBgUtil.setBg(10, Color.parseColor(ConfigureFile.ColorWhite)));
    }

    @Override
    protected void initData(Context mContext) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        homePageAdapter = new HomePageAdapter(context, list, 0);
        homePageAdapter.setOnItemClickListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
        recycleView.setLayoutManager(gridLayoutManager);
        int space = ScreenAdapterTools.getInstance().loadCustomAttrValue(p_20);
        GridDividerItemDecoration gridDividerItemDecoration = new GridDividerItemDecoration(getContext(), space);
        recycleView.addItemDecoration(gridDividerItemDecoration);
        recycleView.setAdapter(homePageAdapter);
        mainPageMode = getViewModelProvider().get(MainPageMode.class);

    }

    @Override
    protected void loadMethod() {
        showListData();
        showMainData();
        checkV();
    }

    /**
     * 显示首页的列表数据
     */
    private void showListData() {
        mainPageMode.getLiveDataHp().observe(this, homePageBeans -> {
            list = homePageBeans;
            homePageAdapter.setListData(list);
            homePageAdapter.notifyDataSetChanged();
        });
        mainPageMode.postHomePageListBean();
    }

    /**
     * 显示首页数据
     */
    private void showMainData() {
        mainPageMode.getLiveDataHc().observe(this, bean -> {
            tvRole.setText(bean.getTerminalName() + "");
            tvLeftName.setText(bean.getLeftTitle() + "");
            tvRightName.setText(bean.getRightTitle() + "");
            tvLeftAccount.setText(bean.getLeftAccount() + "");
            tvRightAccount.setText(bean.getRightAccount() + "");
            lyOrderData.setVisibility(bean.isShowTopView() == true ? View.VISIBLE : View.GONE);
            tvOrderTime.setText(bean.getCreateTime() + "");
            tvOilsData.setText(bean.getOilsData() + "");
        });

    }

    /**
     * 检查版本更新
     */
    private void checkV() {
        mainPageMode.getVersion(getActivity(), getContext());
    }

    @Override
    public void onResume() {
        super.onResume();
        mainPageMode.postHomeContentBean(getContext());
    }

    @OnClick({R.id.iv_menu, R.id.ly_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_menu:
                mDrawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.ly_order://查看操作员的订单
                OrderAmountAc.start(getActivity());
                break;
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        if (ThrottleFirstUtil.isFastClick()) {
            return;
        }
        switch (list.get(position).getAlias()) {
            case FunctionTypeEnum.CHARGE:
                //getConnectedBtDevice();
                ChoseOilNewAc.start(getActivity());
                //VoicePlay.with(getContext()).play("200.00", false);

//                for (int i = 0; i < 1; i++) {
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            VoicePlay.with(getContext()).play("200.00", false);
//                        }
//                    }, 2000);
//                }
//                int i=0;
////                while (true)
////                {
////                    if(i<1)
////                    {
//                     PrintHelper.getInstance().getPrintOrder("272.00", "243.58","北方石油香炉山站", 28.42, "1369800625810329600",
//                             "2021-03-11 08:01:33", "1369800625810329600", "13609877038","2", 10, 0.16,
//                              "00000", "00000", "00000", false);
////                    }
////                    else
////                    {
////                        break;
////                    }
////
////                    i++;
////                }


                break;
            case FunctionTypeEnum.MEMBERCONSUME:
                if (SPUtil.getInstance().getString(ConfigureFile.ISUSERMEMBER, "1").equals("0")) {
                    ToastUtils.showToast(getContext().getApplicationContext(), "门店暂未开通此功能~");
                } else {
                    Scanner(1);
                }
                break;
            case FunctionTypeEnum.SENDCARD:
                IncrementServiceAc.start(getActivity());
                break;
            case FunctionTypeEnum.ONEKEYOIL:
                OneClickOilAc.start(getActivity());
                break;
            case FunctionTypeEnum.QUICKJOINOIL:
                QuickJoinOilAc.start(getActivity());
                break;
            case FunctionTypeEnum.MEMBEROPENCARD:
                GoUpPopupDialog.newInstance(0, false, GoUpPopupDialog.OPENCARD).show(getFragmentManager(), "dialog");
                break;
            case FunctionTypeEnum.MEMBERCHARGE:
                Scanner(3);
                break;
            case FunctionTypeEnum.COUPONWRITEOFF:
                Scanner(8);
                break;
            case FunctionTypeEnum.INVOICE:
                Scanner(12);
                break;
            case FunctionTypeEnum.CARDMANAGER:
                MainCardManagerAc.start(getActivity());
                break;
            case FunctionTypeEnum.SUBCARDMANAGER:
                GoUpPopupDialog.newInstance(1, true, GoUpPopupDialog.OPENCARD).show(getFragmentManager(), "dialog");
                break;
            case FunctionTypeEnum.INTEGRALDEDUCTION:
                Scanner(10);
                break;
        }
    }

    /**
     * 扫一扫功能
     */
    public void Scanner(int num) {
        if (EasyPermissions.hasPermissions(getContext(), permissionArrs)) {
            ScanAc.start(getActivity(), num);
        } else {
            EasyPermissions.requestPermissions(getActivity(), getContext().getResources().getString(R.string.get_photo_permission_tip), 0x11, permissionArrs);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        switch (event.message) {
            case MessageEvent.CHECKORDERTICKET:
                // mainPageMode.IsHaveTicketPrint(getContext());
                break;
            case MessageEvent.JIAOBAN://交接班成功处理
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                ToastUtils.showToast(getContext().getApplicationContext(), "交接班成功");
                mainPageMode.postHomeContentBean(getContext());
                break;
        }
    }


//    private void getConnectedBtDevice(){
//        BluetoothDevice device = null;
//        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
//        for (BluetoothDevice bluetoothDevice : bondedDevices) {
//           String deviceAddress = bluetoothDevice.getAddress();
//            device = bluetoothAdapter.getRemoteDevice(deviceAddress);
//            Log.d("xxxxx",deviceAddress);
//            Log.d("xxxxx",device.getName());
//        }
//        new BlueToothPrintTask(device, PrinterWriter80mm.TYPE_80).execute();
//    }


}
